//
//  RJAQIScattergramView.m
//  AirQuality
//
//  Created by Po on 15/3/11.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJAQIScattergramView.h"
#import "RJCheckDataFitCell.h"
#import "RJDounghnutView.h"

@interface RJAQIScattergramView () <RJHomeBottomFatherViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (retain, nonatomic) RJDounghnutView * dounghnutView;      //环状图
@property (retain, nonatomic) NSMutableArray * data;                //aqi等级数据
@property (retain, nonatomic) NSMutableArray * allCityAirData;      //全省城市
@property (retain, nonatomic) NSTimer * timer;                      //滚动timer

@property (retain, nonatomic) UITableView * detailTable;            //tableView

@property (assign, nonatomic) NetRequestStatus aqiLevelNet;
@property (assign, nonatomic) NetRequestStatus allcityAQINet;

- (void)initData;
- (void)initInterface;
- (void)initNet;
@end

@implementation RJAQIScattergramView

- (instancetype)initWithFrame:(CGRect)frame vc:(UIViewController *)vc
{
    self = [super initWithFrame:frame];
    if (self) {
        self.vc = vc;
        [self initData];
        [self initInterface];
        [self initNet];
    }
    return self;
}

#pragma mark - user-defined initialization function

- (void)initData
{
    [self setDelegate:self];
    self.type = HomeBottomTableAQI;
}

- (void)initInterface
{
    [self setBackgroundColor:[UIColor clearColor]];
}

- (void)initNet
{
    [self netRequest];
}

- (void)netRequest
{
    self.isConnecting = YES;
    _aqiLevelNet = NetRequestStatusDoing;
    _allcityAQINet = NetRequestStatusDoing;
    
    dispatch_group_t netRequestGroup = dispatch_group_create();                 //网络请求任务组
    
    //获取全省AQI分布
    CGRect pieRect = CGRectMake(0, 10, ScreenWidth, (self.bounds.size.height - 40) / 2 - 20);
    [self showLoadingView];
    dispatch_group_enter(netRequestGroup);
    [RJNetWork myNetRequestWithAddress:@"http://newair.scemc.cn:5100/smartadmin/home/getAirQualityLevelWithNames" data:@{} completeBlock:^(id responseObject) {
        _aqiLevelNet = NetRequestStatusSucceed;
        dispatch_group_leave(netRequestGroup);
        [self setDataWithDic:responseObject];
        
        
        //设置圆环
        [self.pieContentView addSubview:[self getDounghnutViewWithFrame:pieRect data:_data colors:[RJTools getColorArrayWithAlpha:1]]];
        
        
        CGFloat width = pieRect.size.width;
        CGFloat height = pieRect.size.height;
        CGFloat radio = (width > height ? height : width) / 2 - (DeviceType >= 6 ? 45 : DeviceType >= 5 ? 30 : 10 );
        [_dounghnutView setCenterPoint:CGPointMake(20 + radio, height / 2 - 5) radio:radio];
        [_dounghnutView build:1];
    }failBlack:^(id response) {
        _aqiLevelNet = NetRequestStatusFailure;
        dispatch_group_leave(netRequestGroup);
    }];
    
    //获取全省城市日报
    CGFloat pieViweMaxY = pieRect.origin.y + pieRect.size.height;
    CGRect tableRect = CGRectMake(0 , pieViweMaxY + 10, pieRect.size.width, self.frame.size.height - pieViweMaxY - 60);
    dispatch_group_enter(netRequestGroup);
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].GetAllCityAQI data:@{} completeBlock:^(id responseObject) {
        
        _allCityAirData = [NSMutableArray arrayWithArray:responseObject[@"data"]];
        _allcityAQINet = NetRequestStatusSucceed;
        dispatch_group_leave(netRequestGroup);
        [self addSubview:[self getTableView:tableRect]];
        //开始滚动
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(updateTableData) userInfo:nil repeats:YES];
    } failBlack:^(id response) {
        _allcityAQINet = NetRequestStatusFailure;
        dispatch_group_leave(netRequestGroup);
    }];
    
    //当所有请求完成后
    dispatch_group_notify(netRequestGroup, dispatch_get_main_queue(), ^{
        [self freeLoadingView];
        if ((_allcityAQINet == NetRequestStatusFailure) || (_aqiLevelNet == NetRequestStatusFailure)) {
            [RJTools showTitle:@"网络异常" msg:@"网络异常，请点击重试！" cancelString:@"取消" confirmString:@"重试" confirmBlock:^{
                [self netRequest];
            } vc:self.vc];
        }
    });
}

#pragma mark - event
/**滚动table*/
- (void)updateTableData
{
    //取出首个
    id temp = _allCityAirData[0];
    [_allCityAirData removeObjectAtIndex:0];
    [_detailTable deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    //追加至末尾
    [_allCityAirData addObject:temp];
    [_detailTable insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_allCityAirData.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allCityAirData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger tag = 0;
    NSMutableAttributedString * pmArrStr;
    static NSString * cellIdent = @"HomeCityCell";
    RJCheckDataFitCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
    if (!cell) {
        cell = [[RJCheckDataFitCell alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40) buttonNum:3];
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.selectedBackgroundView = [[UIView alloc] init];
        [cell showLine];
        [cell setLineColor:SysMainColor];
        
        if (DeviceType < 6) {
            [cell setAllFont:[UIFont systemFontOfSize:16]];
        }
        
        //设置第一个按钮左对齐
        UIButton * button = cell.allButtons[0];
        CGRect rect = button.frame;
        rect.origin.x = 40;
        rect.size.width -= 50;
        [button setFrame:rect];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
        //添加绿圈
        CAShapeLayer * greenLayer = [CAShapeLayer layer];
        greenLayer.frame = CGRectMake(rect.origin.x -20, rect.size.height / 2 - 5, 10, 10);
        [greenLayer setCornerRadius:5];
        [greenLayer setBackgroundColor:GetRGBColor(66, 195, 191, 1).CGColor];
        [cell.layer addSublayer:greenLayer];
        
        //修改第三个按钮的位置
        UIButton * button3 = cell.allButtons[2];
        CGFloat fontSize = button3.titleLabel.font.fontDescriptor.pointSize;
        fontSize -= 4;
        [button3.titleLabel setFont:[UIFont systemFontOfSize:fontSize]];
        button3.titleLabel.textColor = GetRGBColor(80, 80, 80, 1);
    }
    NSDictionary * dic = [[_allCityAirData[indexPath.row] allObjects] lastObject];
    [cell.allButtons[0] setTitle:dic[@"CITYNAME"] forState:UIControlStateNormal];
    [cell.allButtons[1] setTitle:dic[@"AQI"] forState:UIControlStateNormal];
    NSString * pollutionString , *surePollutionString;
    NSString * string = dic[@"PRIMARYPOLLUTANT"];
    if ([string rangeOfString:@"PM10"].location != NSNotFound) {
        pollutionString = [string  stringByReplacingOccurrencesOfString:@"PM10" withString:@"PM₁₀"];
    }else if ([string rangeOfString:@"PM2.5"].location != NSNotFound){
        NSInteger index = [string rangeOfString:@"2"].location;
        pmArrStr = [[NSMutableAttributedString alloc] initWithString:string];
        [pmArrStr addAttribute:NSFontAttributeName
                         value:[UIFont systemFontOfSize:9]
                         range:NSMakeRange(index, 3)];
        [pmArrStr addAttribute:NSBaselineOffsetAttributeName
                         value:[NSNumber numberWithFloat:-3]
                         range:NSMakeRange(index, 3)];
        tag = 1;
//        pollutionString = [string stringByReplacingOccurrencesOfString:@"PM2.5" withString:@"PM₂.₅" ];
    }else{
        pollutionString = string;
    }
    if (pollutionString) {
        if ([pollutionString rangeOfString:@"PM2.5"].location != NSNotFound) {
            NSInteger index = [pollutionString rangeOfString:@"2"].location;
            pmArrStr = [[NSMutableAttributedString alloc] initWithString:pollutionString];
            [pmArrStr addAttribute:NSFontAttributeName
                             value:[UIFont systemFontOfSize:9]
                             range:NSMakeRange(index, 3)];
            [pmArrStr addAttribute:NSBaselineOffsetAttributeName
                             value:[NSNumber numberWithFloat:-3]
                             range:NSMakeRange(index, 3)];
            tag = 1;
            //        surePollutionString = [pollutionString stringByReplacingOccurrencesOfString:@"PM2.5"  withString:@"PM₂.₅"];
        }else{
            surePollutionString = pollutionString;
        }
    }
    NSString * primaryPollutant = surePollutionString;   
    if (primaryPollutant.length > 12) {
        UIButton * button3 = cell.allButtons[2];
        CGFloat fontSize = button3.titleLabel.font.fontDescriptor.pointSize;
        [cell.allButtons[2] setFont:[UIFont systemFontOfSize:fontSize]];
    }
    [cell.allButtons[2] setTitle:([primaryPollutant isEqualToString:@"—"] ? @"无" : primaryPollutant) forState:UIControlStateNormal];
    if (tag == 1) {
        [cell.allButtons[2] setAttributedTitle:pmArrStr forState:UIControlStateNormal];

    }
    [[cell.allButtons[2] titleLabel] setNumberOfLines:0];    
    for (NSUInteger i = 0; i < cell.allButtons.count; i ++) {
        if (( i == 1 ) && (![dic[@"AQI"] isEqualToString:@"—"])) {
            [cell.allButtons[i] setTitleColor:[RJTools getColorWithAirNum:[dic[@"AQI"] floatValue] type:@"AQI" alpha:1] forState:UIControlStateNormal];
            continue;
        }
//        [cell.allButtons[2] setTitleColor:GetRGBColor(80, 80, 80, 1) forState:UIControlStateNormal];
    }
    return cell;
}



- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_timer setFireDate:[NSDate distantFuture]];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_timer setFireDate:[NSDate date]];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ((scrollView.contentOffset.y + _detailTable.frame.size.height) >= scrollView.contentSize.height) {
        NSUInteger cellCount = _detailTable.frame.size.height / 44 + 1;
        NSMutableArray * array = [NSMutableArray arrayWithArray:[_allCityAirData subarrayWithRange:NSMakeRange(_allCityAirData.count - cellCount, cellCount)]];
        [array addObjectsFromArray:[_allCityAirData subarrayWithRange:NSMakeRange(0, _allCityAirData.count - cellCount)]];
        _allCityAirData = [NSMutableArray arrayWithArray:array];
        [scrollView setContentOffset:CGPointMake(0, 0)];
    }
    
    if (scrollView.contentOffset.y < 0) {
        NSUInteger cellCount = _detailTable.frame.size.height / 44 + 1;
        NSMutableArray * array = [NSMutableArray arrayWithArray:[_allCityAirData subarrayWithRange:NSMakeRange(cellCount, _allCityAirData.count - cellCount)]];
        [array addObjectsFromArray:[_allCityAirData subarrayWithRange:NSMakeRange(0, cellCount)]];
        _allCityAirData = [NSMutableArray arrayWithArray:array];
        CGFloat y = scrollView.contentSize.height - _detailTable.frame.size.height - 1;
        [scrollView setContentOffset:CGPointMake(0, y)];
    }
}
#pragma mark - function
- (void)setDataWithDic:(NSDictionary *)dic
{
    NSArray * temp = @[@"A",@"B",@"C",@"D",@"E",@"F"];
    _data = [[NSMutableArray alloc] init];
    for (NSString * key in temp) {
        NSNumber * num = [dic objectForKey:key];
        [_data addObject:num];
    }
    self.detailData = dic[@"GN"];
}

#pragma mark - getter
- (RJDounghnutView *)getDounghnutViewWithFrame:(CGRect)rect data:(NSArray *)data colors:(NSArray *)colors
{
    if (!_dounghnutView) {
        _dounghnutView = [[RJDounghnutView alloc] initWithFrame:rect];
        [_dounghnutView setData:data colors:colors];
    }
    return _dounghnutView;
}
    
- (UIView *)getTableView:(CGRect)rect
{
    UIView * view = [[UIView alloc] initWithFrame:rect];
    
    CGRect tempRect = rect;
    tempRect.origin.y = 40;
    tempRect.size.height -= 40;
    [view addSubview:[self getDetailTable:tempRect]];
    tempRect.origin.y = 0;
    tempRect.size.height = 40;
    
    UIView * sectionBack = [[UIView alloc] initWithFrame:tempRect];
    [sectionBack setBackgroundColor:GetRGBColor(66, 195, 191, 1)];
    [view addSubview:sectionBack];
    
    
    [view addSubview:[self getTableViewSection:tempRect]];
    
    return view;
}

- (UIView *)getTableViewSection:(CGRect)rect
{
    RJCheckDataFitCell * cell = [[RJCheckDataFitCell alloc] initWithFrame:rect buttonNum:3];
    [cell setBackgroundColor:[UIColor clearColor]];
    [cell.allButtons[0] setTitle:@"城市" forState:UIControlStateNormal];
    [cell.allButtons[1] setTitle:@"AQI" forState:UIControlStateNormal];
    [cell.allButtons[2] setTitle:@"污染物" forState:UIControlStateNormal];
    for (NSUInteger i = 0; i < cell.allButtons.count; i ++) {
        [cell.allButtons[i] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    return cell;
}

- (UITableView *)getDetailTable:(CGRect)rect
{
    if (!_detailTable) {
        _detailTable = [[UITableView alloc] initWithFrame:rect];
        [_detailTable setDelegate:self];
        [_detailTable setDataSource:self];
        [_detailTable setBackgroundColor:[UIColor clearColor]];
        [_detailTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_detailTable setShowsVerticalScrollIndicator:NO];
//        _detailTable.bounces = NO;
    }
    return _detailTable;
}

- (NSArray *)getStringWithArray:(NSArray *)data
{
    NSMutableArray * titleArray = [[NSMutableArray alloc] init];
    NSArray * temp = @[@"优",@"良",@"轻度",@"中度",@"重度",@"严重"];
    NSUInteger i = 0;
    for (NSNumber * num in data) {
        [titleArray addObject:[NSString stringWithFormat:@"%@%@个",temp[i],num]];
        i ++;
    }
    return titleArray;
}

- (NSString *)getTitleString
{
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM月dd日"];
    NSString * yesterday = [formatter stringFromDate:YesterdayDate];
    return [NSString stringWithFormat:@"全省城市%@空气质量等级",yesterday];
}


#pragma mark - RJHomeBottomFatherViewDelegate
- (void)netRequestFailure
{
    
}

- (void)setData:(NSArray *)data
{
    
}

- (void)freeData
{
    [_timer invalidate];
}

@end
